<template>
  <div class="profile-page" :class="{ dark: isDark }">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">个人信息</h1>
        <p class="page-description">管理您的个人资料和账户设置</p>
      </div>
    </div>

    <div class="profile-container">
      <!-- 左侧个人信息卡片 -->
      <div class="profile-sidebar">
        <el-card class="profile-card" shadow="hover">
          <div class="profile-avatar-section">
            <div class="avatar-container">
              <el-avatar :src="profileForm.avatar_url" :size="120" class="profile-avatar">
                {{ profileForm.username?.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="avatar-upload-overlay">
                <el-button type="primary" size="small" @click="triggerAvatarUpload">
                  <el-icon><Camera /></el-icon>
                  更换头像
                </el-button>
                <input
                  ref="avatarInput"
                  type="file"
                  accept="image/*"
                  style="display: none"
                  @change="handleAvatarUpload"
                />
              </div>
            </div>
            <div class="profile-name">
              <h3>{{ profileForm.nickname || profileForm.username }}</h3>
              <p class="role-badge">
                <el-tag :type="profileForm.role === 'admin' ? 'danger' : 'primary'">
                  {{ getRoleText(profileForm.role) }}
                </el-tag>
              </p>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作 -->
        <el-card class="actions-card" shadow="hover">
          <div class="action-item" @click="activeTab = 'profile'">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </div>
          <div class="action-item" @click="activeTab = 'password'">
            <el-icon><Lock /></el-icon>
            <span>修改密码</span>
          </div>
        </el-card>
      </div>

      <!-- 右侧表单区域 -->
      <div class="profile-content">
        <!-- 基本信息编辑 -->
        <el-card v-if="activeTab === 'profile'" class="content-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h3>基本信息</h3>
            </div>
          </template>

          <el-form
            :model="profileForm"
            :rules="profileRules"
            ref="profileFormRef"
            label-width="80px"
            class="profile-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="profileForm.username"
                    placeholder="请输入用户名"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="昵称">
              <el-input
                v-model="profileForm.nickname"
                placeholder="请输入昵称（可选）"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="个人简介">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="4"
                placeholder="介绍一下自己吧..."
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="updateProfile"
                :loading="profileLoading"
                class="save-btn"
              >
                <el-icon><Check /></el-icon>
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 修改密码 -->
        <el-card v-if="activeTab === 'password'" class="content-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h3>修改密码</h3>
            </div>
          </template>

          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordFormRef"
            label-width="80px"
            class="password-form"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="changePassword"
                :loading="passwordLoading"
                class="save-btn"
              >
                <el-icon><Check /></el-icon>
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
// 图标导入
import { Camera, User, Lock, Check } from "@element-plus/icons-vue";


// 暗色模式支持
const colorMode = useColorMode();
const isDark = computed(() => colorMode.value === "dark");

// 响应式数据
const activeTab = ref<"profile" | "password">("profile");
const profileLoading = ref(false);
const passwordLoading = ref(false);
const profileFormRef = ref();
const passwordFormRef = ref();
const avatarInput = ref();

// 用户数据类型定义
interface UserProfileData {
  id: number;
  username: string;
  email: string;
  nickname?: string;
  avatar: number | null; // 用于存储的文件ID
  avatar_url: string; // 用于显示的URL
  bio?: string;
  role: 'admin' | 'user';
  status: 'active' | 'inactive' | 'banned';
  created_at?: string;
  updated_at?: string;
}

// 用户数据
const profileForm = ref<UserProfileData>({
  id: 1,
  username: "",
  email: "",
  nickname: "",
  avatar: null,
  avatar_url: "",
  bio: "",
  role: "user",
  status: "active",
  created_at: "",
  updated_at: "",
});

// 密码表单
const passwordForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 表单验证规则
const profileRules = computed(() => ({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度为3-20个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email" as const,
      message: "请输入有效的邮箱地址",
      trigger: "blur",
    },
  ],
}));

const passwordRules = computed(() => ({
  oldPassword: [
    { required: true, message: "请输入当前密码", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
}));

// 方法
const getRoleText = (role: string) => {
  const texts = {
    admin: "管理员",
    user: "编辑者",
  };
  return texts[role as keyof typeof texts] || role;
};

// 获取用户信息
const fetchProfile = async () => {
  try {
    const { success, data, message } = await $fetch<{
      success: boolean;
      data?: any; // 使用any类型，因为返回的数据结构与SafeUserData不完全一致
      message: string;
    }>("/api/user/1/profile");

    if (success && data) {
      profileForm.value = {
        id: data.id,
        username: data.username,
        email: data.email,
        nickname: data.nickname,
        avatar: data.avatar || null, // API返回的文件ID
        avatar_url: data.avatar_url || "", // API返回的URL
        bio: data.bio,
        role: data.role,
        status: data.status,
        created_at: data.created_at,
        updated_at: data.updated_at,
      };
    } else {
      console.error("获取用户信息失败:", message);
      ElMessage.error("获取用户信息失败");
    }
  } catch (error: any) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

// 更新个人信息
const updateProfile = async () => {
  try {
    await profileFormRef.value?.validate();
    profileLoading.value = true;

    const { success, message } = await $fetch<{
      success: boolean;
      message: string;
    }>("/api/user/1/profile", {
      method: "PUT",
      body: {
        username: profileForm.value.username,
        email: profileForm.value.email,
        nickname: profileForm.value.nickname,
        avatar: profileForm.value.avatar,
        bio: profileForm.value.bio,
      },
    });

    if (success) {
      ElMessage.success("个人信息更新成功！");
      await fetchProfile(); // 重新获取数据
    } else {
      throw new Error(message || "更新失败");
    }
  } catch (error: any) {
    console.error("更新个人信息失败:", error);
    ElMessage.error(error.data?.message || error.message || "更新个人信息失败");
  } finally {
    profileLoading.value = false;
  }
};

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value?.validate();
    passwordLoading.value = true;

    const { success, message } = await $fetch<{
      success: boolean;
      message: string;
    }>("/api/user/1/password", {
      method: "PUT",
      body: {
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword,
        confirmPassword: passwordForm.value.confirmPassword,
      },
    });

    if (success) {
      ElMessage.success("密码修改成功！");
      // 清空表单
      passwordForm.value = {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      };
      passwordFormRef.value?.resetFields();
    } else {
      throw new Error(message || "修改失败");
    }
  } catch (error: any) {
    console.error("修改密码失败:", error);
    ElMessage.error(error.data?.message || error.message || "修改密码失败");
  } finally {
    passwordLoading.value = false;
  }
};

// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value?.click();
};

// 处理头像上传
const handleAvatarUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) return;

  // 验证文件类型
  const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp"];
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error("只支持 JPG、PNG、GIF、WebP 格式的图片");
    return;
  }

  // 验证文件大小
  const maxSize = 2 * 1024 * 1024; // 2MB
  if (file.size > maxSize) {
    ElMessage.error("图片大小不能超过2MB");
    return;
  }

  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("category", "avatar");

    const { success, data, message } = await $fetch<{
      success: boolean;
      data?: { id: number; url: string };
      message: string;
    }>("/api/upload", {
      method: "POST",
      body: formData,
    });

    if (success && data) {
      // 更新表单数据
      profileForm.value.avatar = data.id;
      profileForm.value.avatar_url = data.url;
      ElMessage.success("头像上传成功！");
      // 自动保存个人信息
      await updateProfile();
    } else {
      throw new Error(message || "上传失败");
    }
  } catch (error: any) {
    console.error("头像上传失败:", error);
    ElMessage.error(error.data?.message || error.message || "头像上传失败");
  } finally {
    // 清空文件输入
    target.value = "";
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchProfile();
});

// 页面元数据
useHead({
  title: "个人信息 - 博客管理系统",
});
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
  animation: fadeInDown 0.6s ease-out;
}

.header-content h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-content p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.dark .header-content p {
  color: #cbd5e1;
}

.profile-container {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 24px;
  animation: fadeInUp 0.6s ease-out 0.2s both;
}

/* 侧边栏 */
.profile-sidebar {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.profile-card {
  border-radius: 12px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.dark .profile-card {
  background: rgba(30, 41, 59, 0.95);
  border: 1px solid #334155;
}

.profile-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.profile-avatar-section {
  text-align: center;
  padding: 20px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.profile-avatar {
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.profile-avatar:hover {
  transform: scale(1.05);
}

.avatar-upload-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
  padding: 12px 8px 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 0 0 60px 60px;
}

.avatar-container:hover .avatar-upload-overlay {
  opacity: 1;
}

.profile-name h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.dark .profile-name h3 {
  color: #f1f5f9;
}

.role-badge {
  margin: 0;
}

/* 快捷操作卡片 */
.actions-card {
  border-radius: 12px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  overflow: hidden;
}

.dark .actions-card {
  background: rgba(30, 41, 59, 0.95);
  border: 1px solid #334155;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.dark .action-item {
  border-bottom-color: #374151;
  color: #f1f5f9;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item:hover {
  background: rgba(102, 126, 234, 0.05);
  color: #667eea;
}

.dark .action-item:hover {
  background: rgba(96, 165, 250, 0.1);
  color: #60a5fa;
}

/* 内容区域 */
.profile-content {
  min-height: 600px;
}

.content-card {
  border-radius: 12px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.dark .content-card {
  background: rgba(30, 41, 59, 0.95);
  border: 1px solid #334155;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.dark .card-header h3 {
  color: #f1f5f9;
}

.profile-form,
.password-form {
  max-width: 600px;
}

.save-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.save-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 动画效果 */
@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-page {
    padding: 16px;
  }

  .profile-container {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .profile-sidebar {
    order: 2;
  }

  .profile-content {
    order: 1;
  }

  .profile-avatar-section {
    padding: 16px;
  }

  .action-item {
    padding: 12px;
  }

  .profile-form,
  .password-form {
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .profile-card .el-card__body {
    padding: 16px;
  }

  .profile-avatar-section {
    padding: 12px;
  }

  .avatar-container {
    margin-bottom: 12px;
  }

  .profile-name h3 {
    font-size: 18px;
  }

  .card-header h3 {
    font-size: 16px;
  }
}
</style>